//
//  LBEffect3Filter.mm
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 11/22/12.
//  Copyright (c) 2012 UIT. All rights reserved.
//

#include <iostream>

#include "LBEffect3Filter.h"

char fShaderStrEffect3[] = ""
"precision highp float;  "
"varying highp vec2 vtexCoor; "
"uniform sampler2D texture; "
"varying vec4 vposition;"

"varying highp vec2 vtexCoor2;"
"uniform sampler2D texture2; "

"float safeColorF(float color){"
"    if(color > 1.0) color = 1.0;"
"    else if(color < 0.0) color = 0.0;"
"    return color;"
"}"

"vec4 safeColor(vec4 color){"
"    color.r = safeColorF(color.r);"
"    color.g = safeColorF(color.g);"
"    color.b = safeColorF(color.b);"
"    return color;"
"}"

// radial gradient color function
"vec4 radialGradientColor(vec4 centerColor, vec4 outerColor, vec2 myPosition, vec2 centerPosition){"
"    float distance = clamp(distance(myPosition, centerPosition), 0.0, 1.0);"
"    return mix(centerColor, outerColor, distance);"
"}"
// radial gradient color function

// hard light blend function
"vec4 hardLight(vec4 base, vec4 blend, float opacity){"
"   vec4 result =  base;"
"    if (blend.r > 0.5) result.r = 1.0 - (1.0-base.r) *(1.0-2.0*(blend.r-0.5));"
"    else result.r = base.r * (2.0*blend.r);"

"    if (blend.g > 0.5) result.g = 1.0 - (1.0-base.g) *(1.0-2.0*(blend.g-0.5));"
"    else result.g = base.g * (2.0*blend.g);"

"    if (blend.b > 0.5) result.b = 1.0 - (1.0-base.b) *(1.0-2.0*(blend.b-0.5));"
"    else result.b = base.b * (2.0*blend.b);"

"    result = mix(base, result, opacity);"
"    return result;"
"}"
// END hard light blend function

"void main() "
"{ "
"     vec4 textureColor = texture2D(texture, vtexCoor); "
"   lowp vec4 texture2Color = texture2D(texture2, vtexCoor2);"

//contrast
"float contrast = 1.0;"
"textureColor.r = (textureColor.r - 0.5)*contrast + 0.5;"
"textureColor.g = (textureColor.g - 0.5)*contrast + 0.5;"
"textureColor.b = (textureColor.b - 0.5)*contrast + 0.5;"

"textureColor = safeColor(textureColor);"

"   textureColor = hardLight(textureColor, texture2Color, 0.7);"

//tin effect
"vec4 maxColor = vec4(0.967, 0.967, 0.902, 1.0);"
"vec4 minColor = vec4(0.235, 0.137, 0.039, 1.0);"
"textureColor.r = (textureColor.r - minColor.r)*(1.0/(maxColor.r - minColor.r));"
"textureColor.g = (textureColor.g - minColor.g)*(1.0/(maxColor.g - minColor.g));"
"textureColor.b = (textureColor.b - minColor.b)*(1.0/(maxColor.b - minColor.b));"

"textureColor = safeColor(textureColor);"

/*"   vec4 blendColor = radialGradientColor(vec4(0.3, 0.3, 0.3, 1.0), vec4(0.0, 0.0, 0.0, 1.0), vposition.xy, vec2(0.0, 0.0));"
"   textureColor = hardLight(textureColor, blendColor, 0.2);"*/
"    gl_FragColor = textureColor; "
"} ";

LBEffect3Filter::LBEffect3Filter(){
    init(0, fShaderStrEffect3);
}